<?php
/**
 * @todo 检测token有效性
 */

namespace app\weapp\middlewares;


use app\common\facades\auth\Auth;
use app\common\helpers\Response;
use app\common\traits\ApiResponseTrait;
use thans\jwt\exception\TokenBlacklistException;
use thans\jwt\exception\TokenExpiredException;
use thans\jwt\exception\TokenInvalidException;
use thans\jwt\facade\JWTAuth;

class CheckJwt
{
    use ApiResponseTrait;

    public function handle($request, \Closure $next)
    {
        try {
            // 校验token有效性
            JWTAuth::auth();
            // 用户登陆缓存数据失效，重新登陆
            if (!Auth::guard('api')->user()){
                return $this->failed('登录信息已过期，请重新登陆', Response::HTTP_UNAUTHORIZED);
            }
            return $next($request);
        }catch (\Exception $exception){
            if ($exception instanceof TokenInvalidException){
                return $this->failed('登录信息错误，请重新登陆', Response::HTTP_UNAUTHORIZED);
            }
            if ($exception instanceof TokenBlacklistException || $exception instanceof TokenExpiredException){
                return $this->failed('登录信息已过期，请重新登陆', Response::HTTP_UNAUTHORIZED);
            };
            return $this->failed('登录信息错误，请重新登陆', Response::HTTP_UNAUTHORIZED);
        }
    }
}
